package com.candy.candypay.business.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.candy.candypay.business.entity.AliPay;
import com.candy.candypay.config.AliPayConfig;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * @author suYanLong
 * @version 1.0
 * @date 2024/1/10 15:15
 * @Description 对接支付宝
 * 支付宝沙箱环境：
 * https://open.alipay.com/develop/sandbox/app
 * 快解析：
 * https://www.kuaijiexi.com/analysis/#/person
 * 1234qwerdf
 * qwerdf1234
 * 参考：
 * https://mp.weixin.qq.com/s/sVtF0iq9SedD20z_MaXbew
 * 支付：
 * http://localhost:8080/test/pay?subject=%E8%8B%B9%E6%9E%9C11&traceNo=11111&totalAmount=20
 * 回调地址：
 * http://1234qwerdf.gnway.cc/test/notify
 * 退款地址
 * http://localhost:8080/test/return?alipayTraceNo=2024011222001405320502019089&totalAmount=20&traceNo=202401120842
 */
@RestController
@RequestMapping("/pay")
public class PayController {

    private static final String FORMAT = "JSON";

    private static final String CHARSET = "UTF-8";

    //签名方式
    private static final String SIGN_TYPE = "RSA2";

    @Resource
    private AliPayConfig aliPayConfig;

    /**
     * http://localhost:8080/test/pay?subject=%E8%8B%B9%E6%9E%9C11&traceNo=11111&totalAmount=20
     *
     * @param aliPay
     * @param httpResponse
     * @throws Exception
     */
    @GetMapping("/pay") // &subject=xxx&traceNo=xxx&totalAmount=xxx
    public void pay(AliPay aliPay, HttpServletResponse httpResponse) throws Exception {
        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(aliPayConfig.getAlipayUrl(), aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

        // 2. 创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 发送请求的 Request类
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", aliPay.getTraceNo());  // 我们自己生成的订单编号
        bizContent.put("total_amount", aliPay.getTotalAmount()); // 订单的总金额
        bizContent.put("subject", aliPay.getSubject());   // 支付的名称
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");  // 固定配置
        request.setBizContent(bizContent.toString());

        // 执行请求，拿到响应的结果，返回给浏览器
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @GetMapping("/return")
    public String returnPay(AliPay aliPay) throws AlipayApiException {
        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(aliPayConfig.getAlipayUrl(),
                aliPayConfig.getAppId(), aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET,
                aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

        // 2. 创建 Request，设置参数
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", aliPay.getAlipayTraceNo());  // 支付宝回调的订单流水号
        bizContent.put("refund_amount", aliPay.getTotalAmount());  // 订单的总金额
        bizContent.put("out_request_no", aliPay.getTraceNo());   //  我的订单编号

        // 返回参数选项，按需传入
        //JSONArray queryOptions = new JSONArray();
        //queryOptions.add("refund_detail_item_list");
        //bizContent.put("query_options", queryOptions);

        request.setBizContent(bizContent.toString());

        // 3. 执行请求
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {  // 退款成功，isSuccess 为true
            System.out.println("调用成功");
            return "success";
        } else {   // 退款失败，isSuccess 为false
            System.out.println(response.getBody());
            return "fail";
        }

    }

}
